<template>
  <div class="database-instances">
    <!-- 页面标题和操作 -->
    <el-card class="header-card">
      <div class="header-content">
        <div class="header-left">
          <h2>数据库实例管理</h2>
          <p>管理系统中的数据库连接配置，支持MySQL、PostgreSQL等多种数据库类型</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加数据库实例
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="实例名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入实例名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="数据库类型">
          <el-select
            v-model="searchForm.database_type"
            placeholder="请选择数据库类型"
            style="width: 150px"
            clearable
          >
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="Oracle" value="oracle" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="MongoDB" value="mongodb" />
          </el-select>
        </el-form-item>
        <el-form-item label="主机地址">
          <el-input
            v-model="searchForm.host"
            placeholder="请输入主机地址"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadInstances" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据库实例列表 -->
    <el-card class="table-card">
      <el-table
        :data="instances"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="实例名称" width="150">
          <template #default="{ row }">
            <div class="instance-name">
              <el-icon class="db-icon">
                <Coin />
              </el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="database_type" label="数据库类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getDbTypeTag(row.database_type)" size="small">
              {{ row.database_type.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="连接信息" min-width="250">
          <template #default="{ row }">
            <div class="connection-info">
              <div class="connection-line">
                <el-icon><Location /></el-icon>
                <span>{{ row.host }}:{{ row.port }}</span>
              </div>
              <div class="connection-line">
                <el-icon><Folder /></el-icon>
                <span>{{ row.database_name }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />

        <el-table-column label="连接状态" width="120">
          <template #default="{ row }">
            <el-tag
              v-if="row.connectionStatus"
              :type="row.connectionStatus.success ? 'success' : 'danger'"
              size="small"
            >
              <el-icon>
                <CircleCheck v-if="row.connectionStatus.success" />
                <CircleClose v-else />
              </el-icon>
              {{ row.connectionStatus.success ? '正常' : '异常' }}
            </el-tag>
            <el-tag v-else type="info" size="small">未测试</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                size="small"
                @click="testConnection(row)"
                :loading="row.testing"
              >
                <el-icon><Link /></el-icon>
                测试
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="editInstance(row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteInstance(row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadInstances"
          @current-change="loadInstances"
        />
      </div>
    </el-card>

    <!-- 添加/编辑数据库实例对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑数据库实例' : '添加数据库实例'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="实例名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入实例名称"
          />
        </el-form-item>

        <el-form-item label="数据库类型" prop="database_type">
          <el-select
            v-model="form.database_type"
            placeholder="请选择数据库类型"
            style="width: 100%"
          >
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="Oracle" value="oracle" />
            <el-option label="SQL Server" value="sqlserver" />
            <el-option label="MongoDB" value="mongodb" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="主机地址" prop="host">
              <el-input
                v-model="form.host"
                placeholder="请输入主机地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="端口" prop="port">
              <el-input-number
                v-model="form.port"
                :min="1"
                :max="65535"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="数据库名" prop="database_name">
          <el-input
            v-model="form.database_name"
            placeholder="请输入数据库名"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="form.username"
                placeholder="请输入用户名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            :loading="submitting"
          >
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Refresh, Coin, Location, Folder,
  CircleCheck, CircleClose, Link, Edit, Delete
} from '@element-plus/icons-vue'
import { sqlAPI } from '@/api/sql'

// 响应式数据
const instances = ref([])
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  database_type: '',
  host: ''
})

// 表单数据
const form = reactive({
  name: '',
  database_type: 'mysql',
  host: '',
  port: 3306,
  database_name: '',
  username: '',
  password: '',
  description: ''
})

// 表单引用
const formRef = ref(null)

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入实例名称', trigger: 'blur' }
  ],
  database_type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间', trigger: 'blur' }
  ],
  database_name: [
    { required: true, message: '请输入数据库名', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 加载数据库实例列表
const loadInstances = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      ...searchForm
    }

    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await sqlAPI.getDatabaseInstances(params)
    const data = response.data

    if (data.results) {
      instances.value = data.results.map(instance => ({
        ...instance,
        testing: false,
        connectionStatus: null
      }))
      total.value = data.count
    } else {
      instances.value = data.map(instance => ({
        ...instance,
        testing: false,
        connectionStatus: null
      }))
      total.value = data.length
    }

    console.log('加载数据库实例成功:', instances.value.length)
  } catch (error) {
    console.error('加载数据库实例失败:', error)
    ElMessage.error('加载数据库实例失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    database_type: '',
    host: ''
  })
  currentPage.value = 1
  loadInstances()
}

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑实例
const editInstance = (instance) => {
  isEdit.value = true
  Object.assign(form, {
    id: instance.id,
    name: instance.name,
    database_type: instance.database_type,
    host: instance.host,
    port: instance.port,
    database_name: instance.database_name,
    username: instance.username,
    password: '', // 出于安全考虑，不显示原密码
    description: instance.description || ''
  })
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    database_type: 'mysql',
    host: '',
    port: 3306,
    database_name: '',
    username: '',
    password: '',
    description: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    submitting.value = true

    if (isEdit.value) {
      await sqlAPI.updateDatabaseInstance(form.id, form)
      ElMessage.success('数据库实例更新成功')
    } else {
      await sqlAPI.createDatabaseInstance(form)
      ElMessage.success('数据库实例创建成功')
    }

    dialogVisible.value = false
    loadInstances()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response?.data?.error) {
      ElMessage.error(error.response.data.error)
    } else {
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 测试数据库连接
const testConnection = async (instance) => {
  instance.testing = true
  try {
    const response = await sqlAPI.testDatabaseConnection(instance.id)
    instance.connectionStatus = response.data

    if (response.data.success) {
      ElMessage.success(`连接测试成功 (${response.data.connection_time}s)`)
    } else {
      ElMessage.error(`连接测试失败: ${response.data.message}`)
    }
  } catch (error) {
    console.error('测试连接失败:', error)
    instance.connectionStatus = {
      success: false,
      message: '连接测试失败'
    }
    ElMessage.error('连接测试失败')
  } finally {
    instance.testing = false
  }
}

// 删除数据库实例
const deleteInstance = async (instance) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据库实例 "${instance.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await sqlAPI.deleteDatabaseInstance(instance.id)
    ElMessage.success('数据库实例删除成功')
    loadInstances()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取数据库类型标签样式
const getDbTypeTag = (type) => {
  const tagMap = {
    mysql: 'primary',
    postgresql: 'success',
    oracle: 'warning',
    sqlserver: 'info',
    mongodb: 'danger'
  }
  return tagMap[type] || 'info'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadInstances()
})
</script>

<style scoped>
.database-instances {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.instance-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.db-icon {
  color: #409eff;
}

.connection-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.connection-line {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #606266;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
  }

  .header-right {
    align-self: stretch;
  }

  .connection-info {
    font-size: 12px;
  }
}
</style>
